<?php
/**
 * 科室管理
 * 州弟医院信息系统 - 州弟学安全
 */

// 包含函数文件
require_once '../includes/functions.php';

// 检查用户是否已登录并具有管理员权限
if (!isLoggedIn() || !hasRole('admin')) {
    $_SESSION['error_msg'] = '您无权访问该页面';
    redirect('../login.php');
}

// 处理科室操作
$success = '';
$error = '';

// 检查字段是否存在
$check_field_sql = "SHOW COLUMNS FROM departments LIKE 'working_hours'";
$check_field_result = $conn->query($check_field_sql);
if ($check_field_result && $check_field_result->num_rows == 0) {
    // 添加缺失的字段
    $add_field_sql = "ALTER TABLE departments ADD COLUMN working_hours VARCHAR(100) NULL AFTER phone";
    $conn->query($add_field_sql);
    $success = '数据库结构已更新，添加了工作时间字段';
}

// 处理删除科室请求
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $department_id = (int)$_GET['delete'];
    
    // 检查是否有医生关联到该科室
    $sql = "SELECT COUNT(*) as count FROM doctors WHERE department_id = $department_id";
    $result = $conn->query($sql);
    $count = 0;
    
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $count = $row['count'];
    }
    
    if ($count > 0) {
        $error = '无法删除该科室，因为有 ' . $count . ' 名医生关联到此科室';
    } else {
        // 检查是否有预约关联到该科室
        $sql = "SELECT COUNT(*) as count FROM appointments WHERE department_id = $department_id";
        $result = $conn->query($sql);
        $count = 0;
        
        if ($result && $result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $count = $row['count'];
        }
        
        if ($count > 0) {
            $error = '无法删除该科室，因为有 ' . $count . ' 个预约关联到此科室';
        } else {
            // 删除科室
            $sql = "DELETE FROM departments WHERE id = $department_id";
            
            if ($conn->query($sql)) {
                // 记录操作日志
                logAction($_SESSION['user_id'], '删除科室（ID：' . $department_id . '）');
                
                $success = '科室删除成功！';
            } else {
                $error = '删除科室失败：' . $conn->error;
            }
        }
    }
}

// 处理添加/编辑科室表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['add_department']) || isset($_POST['edit_department'])) {
        $name = $_POST['name'] ?? '';
        $description = $_POST['description'] ?? '';
        $floor = $_POST['floor'] ?? '';
        $phone = $_POST['phone'] ?? '';
        $working_hours = $_POST['working_hours'] ?? '';
        $department_id = isset($_POST['department_id']) ? (int)$_POST['department_id'] : 0;
        
        // 基本验证
        if (empty($name) || empty($floor)) {
            $error = '请填写所有必填字段';
        } else {
            $name = $conn->real_escape_string($name);
            $description = $conn->real_escape_string($description);
            $floor = $conn->real_escape_string($floor);
            $phone = $conn->real_escape_string($phone);
            $working_hours = $conn->real_escape_string($working_hours);
            
            // 添加新科室
            if (isset($_POST['add_department'])) {
                $sql = "INSERT INTO departments (name, description, floor, phone, working_hours) 
                        VALUES ('$name', '$description', '$floor', '$phone', '$working_hours')";
                
                if ($conn->query($sql)) {
                    $new_department_id = $conn->insert_id;
                    
                    // 记录操作日志
                    logAction($_SESSION['user_id'], '添加科室（ID：' . $new_department_id . '）');
                    
                    $success = '科室添加成功！';
                } else {
                    $error = '添加科室失败：' . $conn->error;
                }
            }
            // 编辑现有科室
            else {
                $sql = "UPDATE departments SET name = '$name', description = '$description', 
                        floor = '$floor', phone = '$phone', working_hours = '$working_hours' 
                        WHERE id = $department_id";
                
                if ($conn->query($sql)) {
                    // 记录操作日志
                    logAction($_SESSION['user_id'], '更新科室（ID：' . $department_id . '）');
                    
                    $success = '科室更新成功！';
                } else {
                    $error = '更新科室失败：' . $conn->error;
                }
            }
        }
    }
}

// 获取所有科室
$departments = [];
$sql = "SELECT * FROM departments ORDER BY name ASC";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $departments[] = $row;
    }
}

// 如果是编辑请求，获取科室信息
$edit_department = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $department_id = (int)$_GET['edit'];
    $sql = "SELECT * FROM departments WHERE id = $department_id";
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        $edit_department = $result->fetch_assoc();
    }
}

?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>科室管理 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="/assets\css/bootstrap_69c9e605.min.css">
    <link rel="stylesheet" href="/assets\css/all_3b858821.min.css">
    <link rel="stylesheet" href="/assets\css/style.css">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-2 px-0 admin-sidebar">
                <div class="py-3 px-3 bg-dark">
                    <a href="<?php echo SITE_URL; ?>admin/" class="text-white text-decoration-none">
                        <i class="fas fa-hospital-alt mr-2"></i>管理后台
                    </a>
                </div>
                <div class="p-3">
                    <div class="text-white mb-3">
                        <i class="fas fa-user-circle mr-1"></i> <?php echo $_SESSION['username']; ?>
                    </div>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/">
                                <i class="fas fa-tachometer-alt mr-2"></i>仪表盘
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/users.php">
                                <i class="fas fa-users mr-2"></i>用户管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/patients.php">
                                <i class="fas fa-user-injured mr-2"></i>患者管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/doctors.php">
                                <i class="fas fa-user-md mr-2"></i>医生管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="<?php echo SITE_URL; ?>admin/departments.php">
                                <i class="fas fa-hospital mr-2"></i>科室管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/appointments.php">
                                <i class="fas fa-calendar-check mr-2"></i>预约管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/medicines.php">
                                <i class="fas fa-pills mr-2"></i>药品管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/records.php">
                                <i class="fas fa-notes-medical mr-2"></i>病历管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/logs.php">
                                <i class="fas fa-history mr-2"></i>系统日志
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/settings.php">
                                <i class="fas fa-cog mr-2"></i>系统设置
                            </a>
                        </li>
                        <li class="nav-item mt-3">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>">
                                <i class="fas fa-home mr-2"></i>返回前台
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>logout.php">
                                <i class="fas fa-sign-out-alt mr-2"></i>退出登录
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
            
            <!-- 主内容区 -->
            <div class="col-md-10 ml-sm-auto px-4 py-3">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">科室管理</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <button type="button" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#addDepartmentModal">
                            <i class="fas fa-plus mr-1"></i> 添加科室
                        </button>
                    </div>
                </div>
                
                <?php if ($success): ?>
                    <div class="alert alert-success">
                        <?php echo $success; ?>
                    </div>
                <?php endif; ?>
                
                <?php if ($error): ?>
                    <div class="alert alert-danger">
                        <?php echo $error; ?>
                    </div>
                <?php endif; ?>
                
                <!-- 科室列表 -->
                <div class="row">
                    <?php if (empty($departments)): ?>
                        <div class="col-12">
                            <div class="alert alert-info">暂无科室信息</div>
                        </div>
                    <?php else: ?>
                        <?php foreach ($departments as $department): ?>
                            <div class="col-md-4 mb-4">
                                <div class="card h-100">
                                    <div class="card-header bg-light">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h5 class="mb-0"><?php echo $department['name']; ?></h5>
                                            <div>
                                                <a href="?edit=<?php echo $department['id']; ?>" class="btn btn-sm btn-info" title="编辑科室">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <a href="?delete=<?php echo $department['id']; ?>" class="btn btn-sm btn-danger" title="删除科室" onclick="return confirm('确定要删除此科室吗？此操作不可恢复！');">
                                                    <i class="fas fa-trash-alt"></i>
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card-body">
                                        <p class="card-text"><?php echo $department['description'] ?: '暂无描述'; ?></p>
                                        <div class="department-info">
                                            <p><i class="fas fa-map-marker-alt mr-2 text-muted"></i> 位置：<?php echo $department['floor']; ?></p>
                                            <p><i class="fas fa-phone mr-2 text-muted"></i> 电话：<?php echo isset($department['phone']) ? $department['phone'] : '暂无'; ?></p>
                                            <p><i class="fas fa-clock mr-2 text-muted"></i> 工作时间：<?php echo isset($department['working_hours']) ? $department['working_hours'] : '暂无'; ?></p>
                                        </div>
                                    </div>
                                    <div class="card-footer bg-white">
                                        <a href="doctors.php?department=<?php echo $department['id']; ?>" class="btn btn-sm btn-outline-primary">
                                            <i class="fas fa-user-md mr-1"></i> 查看医生
                                        </a>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                
                <!-- 版权信息 -->
                <footer class="mt-5 text-center text-muted">
                    <p>
                        &copy; <?php echo date('Y'); ?> <?php echo SITE_NAME; ?>. 版权所有
                        <br>
                        <small>Powered by <a href="#" class="text-muted">州弟学安全</a> | 版本 <?php echo VERSION; ?></small>
                    </p>
                </footer>
            </div>
        </div>
    </div>
    
    <!-- 添加科室模态框 -->
    <div class="modal fade" id="addDepartmentModal" tabindex="-1" role="dialog" aria-labelledby="addDepartmentModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addDepartmentModalLabel">添加科室</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="name">科室名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="name" name="name" required>
                        </div>
                        <div class="form-group">
                            <label for="description">科室描述</label>
                            <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                        </div>
                        <div class="form-group">
                            <label for="floor">科室位置 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="floor" name="floor" placeholder="例如：门诊楼3楼" required>
                        </div>
                        <div class="form-group">
                            <label for="phone">联系电话</label>
                            <input type="text" class="form-control" id="phone" name="phone" placeholder="例如：010-12345678">
                        </div>
                        <div class="form-group">
                            <label for="working_hours">工作时间</label>
                            <input type="text" class="form-control" id="working_hours" name="working_hours" placeholder="例如：周一至周五 8:00-17:00">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="submit" name="add_department" class="btn btn-primary">添加</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- 编辑科室模态框 -->
    <?php if ($edit_department): ?>
    <div class="modal fade" id="editDepartmentModal" tabindex="-1" role="dialog" aria-labelledby="editDepartmentModalLabel" aria-hidden="true" data-show="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editDepartmentModalLabel">编辑科室</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <input type="hidden" name="department_id" value="<?php echo $edit_department['id']; ?>">
                        <div class="form-group">
                            <label for="edit_name">科室名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="edit_name" name="name" value="<?php echo $edit_department['name']; ?>" required>
                        </div>
                        <div class="form-group">
                            <label for="edit_description">科室描述</label>
                            <textarea class="form-control" id="edit_description" name="description" rows="3"><?php echo isset($edit_department['description']) ? $edit_department['description'] : ''; ?></textarea>
                        </div>
                        <div class="form-group">
                            <label for="edit_floor">科室位置 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="edit_floor" name="floor" value="<?php echo $edit_department['floor']; ?>" required>
                        </div>
                        <div class="form-group">
                            <label for="edit_phone">联系电话</label>
                            <input type="text" class="form-control" id="edit_phone" name="phone" value="<?php echo isset($edit_department['phone']) ? $edit_department['phone'] : ''; ?>">
                        </div>
                        <div class="form-group">
                            <label for="edit_working_hours">工作时间</label>
                            <input type="text" class="form-control" id="edit_working_hours" name="working_hours" value="<?php echo isset($edit_department['working_hours']) ? $edit_department['working_hours'] : ''; ?>">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="submit" name="edit_department" class="btn btn-primary">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script>
        $(document).ready(function() {
            $('#editDepartmentModal').modal('show');
        });
    </script>
    <?php endif; ?>

    <script src="/assets\js/jquery-3_7b53a2dc.5.1.min.js"></script></script></script></script>
    <script src="/assets\js/popper_9c21e708.min.js"></script></script></script></script>
    <script src="/assets\js/bootstrap_a618e9ff.min.js"></script></script></script></script>
    <script src="/assets\js/main.js"></script></script>
</body>
</html> 